<template>
  <div id="paper-management" class="container">
    <table-filter>
      <el-input
        placeholder="请输入试卷名称"
        clearable
        v-model="apiSetting.data.papername"
      ></el-input>
      <el-select
        v-model="apiSetting.data.papertype"
        clearable
        placeholder="请选择试卷类型"
      >
        <el-option
          v-for="item in paperType"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button plain type="warning" @click="search">查询</el-button>
    </table-filter>
    <el-row>
      <el-button @click="showEaDialog = true">新建试卷</el-button>
      <el-dropdown @command="exportFile" trigger="click">
        <el-button plain type="primary">
          导出试卷记录<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="xls">Excel</el-dropdown-item>
          <el-dropdown-item command="csv">Csv</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-row>
    <data-table
      ref="dtb"
      :sort-column="sortColumn"
      :api-setting="apiSetting"
      pagination
    >
      <el-table-column
        fixed
        prop="paperid"
        label="试卷编号"
        width="110"
        show-overflow-tooltip
      />
      <el-table-column prop="papername" label="试卷名" show-overflow-tooltip />

      <el-table-column
        prop="papertype"
        label="试卷类型"
        width="110"
        sortable
        show-overflow-tooltip
        :formatter="stateFormat"
      >
      </el-table-column>

      <el-table-column
        prop="starttime"
        label="开始时间"
        width="170"
        sortable
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          {{ row.starttime | formatterDate }}
        </template>
      </el-table-column>
      <el-table-column
        prop="endtime"
        label="结束时间"
        width="170"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          {{ row.endtime | formatterDate }}
        </template>
      </el-table-column>
      <el-table-column
        prop="userCode"
        label="创建人"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="{ row }">
          <el-button
            @click="hasEaPermission(row.userCode, 'edit', row)"
            type="text"
            class="warning"
            size="small"
            >编辑
          </el-button>
          <el-dropdown @command="exportPaper($event, row)" trigger="click">
            <el-button type="text" size="small"
              >导出<i class="el-icon-arrow-down el-icon--right"></i
            ></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="1">含答案</el-dropdown-item>
              <el-dropdown-item :command="0">仅题目</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            @click="hasEaPermission(row.userCode, 'delPaper', row)"
            type="text"
            size="small"
            class="danger"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </data-table>
    <ea-paper
      ref="eaDialog"
      :show.sync="showEaDialog"
      @on-reload="dtb.loadData()"
    />
  </div>
</template>

<script>
import dtb from "../../../mixins/refs/dtb";
import paperType from "../../../staticData/paperType";
import EaPaper from "./EaPaper";
import eaDialog from "../../../mixins/refs/eaDialog";
import { mapGetters, mapActions } from "vuex";
import deleteRow from "@/mixins/dataTable/deleteRow";
import tbSearch from "@/mixins/dataTable/tbSearch";
import permission from "@/mixins/permission/permission";

export default {
  name: "index",
  components: { EaPaper },
  mixins: [tbSearch, dtb, eaDialog, deleteRow, permission],
  data() {
    return {
      apiSetting: {
        method: "post",
        url: "/sys/papermanage/getPaperList",
        data: {
          papername: "",
          papertype: null
        }
      },
      sortColumn: ["papertype", "starttime"],
      paperType
    };
  },
  computed: {
    ...mapGetters(["getUserAccount"])
  },
  methods: {
    exportFile(fileType) {
      const { papername, papertype } = this.apiSetting.data;
      const url = {
        xls: "/sys/papermanage/exportPaperExcel",
        csv: "/sys/papermanage/exportPaperCsv"
      };
      this.downLoadFile(
        {
          method: "post",
          url: url[fileType],
          data: {
            cols: [
              "paperid",
              "papername",
              "starttime",
              "endtime",
              "username",
              "papertypename"
            ],
            papername,
            papertype
          }
        },
        "试卷记录." + fileType
      );
    },
    async edit({ paperid }) {
      const res = await this.api.getPaperById(paperid);
      const needSplitFields = [
        "singlequelist",
        "multiplequelist",
        "truefalsequelist"
      ];
      const {
        subquedetails,
        scorestandard,
        endtime,
        starttime,
        quebanklist,
        israndom,
        sublist,
        chapteridlist
      } = res;
      //固定试题不对随机试题的信息进行解析
      res.subquedetails = israndom ? JSON.parse(subquedetails) : [];
      res.scorestandard = JSON.parse(scorestandard);
      res.israndom = israndom.toString();
      needSplitFields.map(key => {
        if (res[key]) res[key] = res[key].split(",").filter(item => item);
        else res[key] = [];
      });
      const qbList = quebanklist.split(",");
      res.quebanklist = qbList.map(item => {
        return +item;
      });
      const subjects = await this.api.getSubjectsOfQueBank(quebanklist);
      const chapters = await this.api.getGroupChapter(sublist);
      res.sublist = subjects.reduce((selectSubject, sub) => {
				let newARR=sublist.split(',')
				newARR.map(item=>{
					if(item==sub.subid) selectSubject.push(JSON.stringify(sub));
				})
        return selectSubject;
      }, []);
      //使用split切割字符串后，数据元素为string类型，双向绑定时，值为int
      if (chapteridlist == null) {
        res.chapteridlist = "";
      } else {
        res.chapteridlist = chapteridlist.split(",").map(item => item);
      }
      this.showEaDialog = true;
      this.eaDialog.setEditData({
        singleData: {
          ...res,
          selectTime: [starttime, endtime]
        },
        subjects,
        chapters
      });
    },
    delPaper({ paperid }) {
      this.delRow(`/sys/papermanage/deletePaper/${paperid}`, "考试");
    },
    exportPaper(hasAnswer, row) {
      const { paperid, papername, israndom, isstusame } = row;
      if (israndom && !isstusame) {
        this.$notify.warning("学生试卷不相同，无法导出！");
        return;
      }
      this.downLoadFile(
        {
          method: "post",
          url: `/sys/papermanage/exportword/${paperid}/${hasAnswer}`
        },
        `${papername}${hasAnswer ? "（含答案）" : ""}.docx`
      );
    },
    stateFormat(row) {
      switch (row.papertype) {
        case 1:
          return "考试";
        case 2:
          return "终极押题";
        case 3:
          return "全真模拟";
      }
    }
  }
};
</script>

<style scoped>
.el-dropdown {
  margin: 0 10px;
}
</style>
